<template>
  <div>
    <px-row style="height: 64px">
      <px-col :span="24" class="water_col">
        <div class="waterdom borderRidus boxShadow">
          <px-form ref="queryRef" class="custom-form-ui" :model="queryParams" :inline="true" label-width="90px">
            <px-form-item label="废弃物">
              <px-select v-model="queryParams.reportType" placeholder="请选择" style="width: 240px" filterable @change="queysetSystemChemicals">
                <px-option v-for="dict in liquidList" :key="dict.itemValue" :label="dict.itemName" :value="dict.itemValue" />
              </px-select>
            </px-form-item>
            <px-form-item label="危废名称" style="width: 310px">
              <px-select
                v-model="queryParams.dictWasteCode"
                multiple
                collapse-tags
                collapse-tags-tooltip
                placeholder="请选择"
                clearable
                style="width: 240px"
              >
                <px-option v-for="dict in querychemicalList" :key="dict.itemValue" :label="dict.itemName" :value="dict.itemValue" />
              </px-select>
            </px-form-item>
            <px-form-item label="统计维度">
              <px-select v-model="queryParams.timeUnit" placeholder="请选择" style="width: 210px" filterable @change="timechange">
                <px-option v-for="dict in dimensionList" :key="dict.itemValue" :label="dict.itemName" :value="dict.itemValue" />
              </px-select>
            </px-form-item>
            <px-form-item v-if="queryParams.timeUnit == 'YEAR'" label="年份">
              <!-- <px-date-picker v-model="queryParams.Time" type="year" placeholder="请选择" /> -->
              <yearPicker :labelWidth="0" labelText="" :initYear="dateValue" @updateTimeRange="updateStatisticYear" />
            </px-form-item>
            <px-form-item v-if="queryParams.timeUnit == 'MONTH'" label="时间">
              <px-date-picker
                v-model="dateRange"
                type="monthrange"
                range-separator="-"
                start-placeholder="开始月份"
                end-placeholder="结束月份"
                placeholder="请选择"
                format="YYYY-MM"
                value-format="YYYY-MM"
                @change="settime"
              />
            </px-form-item>
            <px-form-item v-if="queryParams.timeUnit == 'DAY'" style="width: 440px !important" label="时间">
              <px-date-picker
                v-model="dateRange2"
                type="daterange"
                range-separator="-"
                start-placeholder="开始时间"
                end-placeholder="结束时间"
                placeholder="请选择"
                format="YYYY-MM-DD"
                value-format="YYYY-MM-DD HH:mm:ss"
                @change="settime2"
              />
            </px-form-item>
            <px-button style="margin-top: -17px" type="primary" icon="" @click="handleQuery('search')">搜索</px-button>
            <px-button style="margin-top: -17px" icon="" @click="resetQuery">重置</px-button>
          </px-form>
        </div>
      </px-col>
    </px-row>
    <px-row style="margin-top: 16px" :gutter="16">
      <px-col :span="24" class="water_col" style="margin-bottom: 16px">
        <div class="waterdom borderRidus boxShadow" style="height: 564px">
          <modelTitle title="载出量趋势图" />
          <chartloadSummary
            :xlist="typeList.header.xaxis"
            :chartlist="typeList.dataList"
            style="width: 100%; height: 500px"
            :width="'100%'"
            :height="'500px'"
          />
        </div>
      </px-col>
      <px-col :span="24" class="water_col" style="margin-bottom: 16px">
        <div class="waterdom borderRidus boxShadow">
          <modelTitle v-if="activeWater == 'load'" title="载出报表(单位：t)" />
          <modelTitle v-else title="消耗报表" />
          <px-button v-has="'LOAD_OUT_EXPORT'" type="primary" class="export" plain icon="" @click="handleExport">导出报表</px-button>
          <px-scrollbar style="margin-top: 16px">
            <div class="tableTop">
              <div class="topList">危废名称</div>
              <div v-for="(item, index) in typeList.header.header" :key="index" class="topList">{{ item }}</div>
            </div>
            <div v-for="(item, index) in typeList.dataList" :key="index" class="tableMain">
              <div class="topList">{{ item.wasteName != null ? item.wasteName : "-" }}</div>
              <div v-for="(items, index) in item.data" :key="index" class="topList">{{ items != null ? items : "-" }}</div>
            </div>
          </px-scrollbar>
        </div>
      </px-col>
    </px-row>
  </div>
</template>
<script setup lang="ts">
import yearPicker from "@/views/common/energy/components/yearPicker.vue";
import modelTitle from "@/views/common/components/modelTitle/index.vue";
import chartswwt from "./components/chartswwt.vue";
import chartloadSummary from "./chartloadSummary.vue";
import { PxMessage, PxMessageBox } from "px-ui";
import { getToken } from "@/utils/auth";
import { getCurrentInstance, ref, toRefs, reactive, onMounted } from "vue";
import { queryChildByTypeCodeAndItemValue } from "@/api/waterClass";
import { wasteloadOutReport } from "@/api/hazardousWasteS";
import { generalChemicalqueryChemicalName, chemicalReportqueryLoadReport, chemicalReportqueryConsumeReport } from "@/api/chemicals";
import { receiveName, receiveName2, receiveNamedanger } from "@/api/waterClass";
const props = defineProps({
  classCode: {
    type: String,
    default: "WATER"
  }
});
const dateValue = ref<any>({ startYear: new Date().getFullYear() - 6, endYear: new Date().getFullYear() });
const updateStatisticYear: any = (startYear: number, endYear: number) => {
  console.log("选中年份", startYear, endYear);
  // queryParams.value.dateRange = [startYear.toString(), endYear.toString()];
  queryParams.value.startTime = `${startYear}-01-01 00:00:00`;
  queryParams.value.endTime = `${endYear}-12-31 23:59:59`;
};
const settime = val => {
  console.log(val);
  queryParams.value.startTime = `${val[0]}-01 00:00:00`;
  queryParams.value.endTime = `${val[1]}-31 23:59:59`;
};
const timechange = val => {
  if (val == "MONTH") {
    queryParams.value.startTime = `${dateRange.value[0]}-01-01 00:00:00`;
    queryParams.value.endTime = `${dateRange.value[1]}-12-31 23:59:59`;
  }
  if (val == "YEAR") {
    queryParams.value.startTime = `${dateValue.value.startYear}-01-01 00:00:00`;
    queryParams.value.endTime = `${dateValue.value.endYear}-12-31 23:59:59`;
  }
  if (val == "DAY") {
    queryParams.value.startTime = `${dateRange2.value[0]}-01 00:00:00`;
    queryParams.value.endTime = `${dateRange2.value[1]}-31 23:59:59`;
  }
};
const settime2 = val => {
  console.log(val);
  queryParams.value.startTime = val[0];
  queryParams.value.endTime = val[1];
};
const data = reactive({
  queryParams: {
    reportType: "",
    dictWasteCode: [],
    startTime: "",
    endTime: "",
    classCode: props.classCode,
    timeUnit: "MONTH"
  },
  tableData: [
    {
      taskNo: "1",
      taskName: "任务名称",
      responsible: "责任人",
      status: "ONGOING"
    }
  ],
  syetemList: [],
  samplingLocationList: [],
  dateRange: [],
  dateRange2: [],
  testItemList: [],
  chartsList: [],
  tableData1: [],
  tableData2: [],
  tableData3: [],
  tableData4: [],
  querychemicalList: [],
  liquidList: [],
  typeList: {
    header: {
      header: [],
      xaxis: []
    }
  },
  dimensionList: [
    {
      itemName: "日",
      itemValue: "DAY"
    },
    {
      itemName: "月",
      itemValue: "MONTH"
    },
    {
      itemName: "年",
      itemValue: "YEAR"
    }
  ]
});
const {
  dateRange2,
  dimensionList,
  typeList,
  liquidList,
  queryParams,
  tableData1,
  tableData2,
  tableData3,
  tableData4,
  tableData,
  syetemList,
  samplingLocationList,
  dateRange,
  querychemicalList,
  testItemList,
  chartsList
} = toRefs(data);
const loading = ref(true);
const getsixmonth = () => {
  const date = new Date();
  let SixMon = new Date(date);
  SixMon.setMonth(SixMon.getMonth() - 6);
  console.log(SixMon.toISOString().split("T")[0].slice(0, -3));
  return SixMon.toISOString().split("T")[0].slice(0, -3);
};
const getdate = () => {
  const date = new Date();
  return date.toISOString().split("T")[0].slice(0, -3);
};
const queysetSystemChemicals = val => {
  queryParams.value.dictWasteCode = [];
  reportTypeName.value = liquidList.value.filter(item => item.itemValue == val)[0].itemName;
  if (val == "GL") {
    receiveName({
      classCode: props.classCode,
      physicalState: "LIQUID"
    }).then((response: any) => {
      //console.log(response);
      querychemicalList.value = response;
      queryParams.value.dictWasteCode = querychemicalList.value.map(item => item.itemValue);
    });
  }
  if (val == "GS") {
    receiveName2({
      classCode: props.classCode,
      physicalState: "SOLID "
    }).then((response: any) => {
      //console.log(response);
      querychemicalList.value = response;
      queryParams.value.dictWasteCode = querychemicalList.value.map(item => item.itemValue);
    });
  }
  if (val == "HL") {
    receiveNamedanger({
      classCode: props.classCode,
      physicalState: "LIQUID"
    }).then((response: any) => {
      //console.log(response);
      querychemicalList.value = response;
      queryParams.value.dictWasteCode = querychemicalList.value.map(item => item.itemValue);
    });
  }
  if (val == "HS") {
    receiveNamedanger({
      classCode: props.classCode,
      physicalState: "SOLID"
    }).then((response: any) => {
      //console.log(response);
      querychemicalList.value = response;
      queryParams.value.dictWasteCode = querychemicalList.value.map(item => item.itemValue);
    });
  }
};
function formatDate(date) {
  const year = date.getFullYear();
  const month = (date.getMonth() + 1).toString().padStart(2, "0");
  const day = date.getDate().toString().padStart(2, "0");
  const h = date.getHours().toString().padStart(2, "0");
  const m = date.getMinutes().toString().padStart(2, "0");
  const s = date.getSeconds().toString().padStart(2, "0");
  return `${year}-${month}-${day} ${h}:${m}:${s}`;
}
const activeWater = ref("load");
const reportTypeName = ref("");
const getqueryCategoryList = () => {
  liquidList.value = [
    {
      itemName: " 一般废液",
      itemValue: "GL"
    },
    {
      itemName: " 一般固废",
      itemValue: "GS"
    },
    {
      itemName: " 危险废液",
      itemValue: "HL"
    },
    {
      itemName: " 危险固废",
      itemValue: "HS"
    }
  ];
  queryParams.value.reportType = "GL";
  reportTypeName.value = "一般废液";
  receiveName({
    classCode: props.classCode,
    physicalState: "LIQUID"
  }).then((response: any) => {
    //console.log(response);
    querychemicalList.value = response;
    queryParams.value.dictWasteCode = querychemicalList.value.map(item => item.itemValue);
  });
  dateRange.value = [`${getsixmonth()}`, `${getdate()}`];
  console.log(dateRange.value);
  const end = new Date();
  end.setHours(23, 59, 59, 0);
  end.setTime(end.getTime());
  const start = new Date();
  start.setHours(0, 0, 0, 0);
  start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
  dateRange2.value = [formatDate(start), formatDate(end)];
  getList();
};
getqueryCategoryList();
const factoryList = [
  {
    itemName: "全厂",
    itemValue: 1
  },
  {
    itemName: "分厂1",
    itemValue: 2
  },
  {
    itemName: "分厂2",
    itemValue: 3
  }
];

const tabPaneList = [
  {
    label: "载入报表",
    name: "load"
  },
  {
    label: "消耗报表",
    name: "expend"
  }
];
const radio = ref("时");
const getRandomInt = (min, max) => {
  min = Math.ceil(min);
  max = Math.floor(max);
  return Math.floor(Math.random() * (max - min + 1)) + min;
};

const defaultTime: [Date, Date] = [new Date(2000, 1, 1, 0, 0, 1), new Date(2000, 1, 1, 23, 59, 59)];

const handleQuery = () => {
  let parmas = {
    reportType: queryParams.value.reportType,
    dictWasteCode: queryParams.value.dictWasteCode,
    startTime: dateRange.value[0],
    endTime: dateRange.value[1]
  };
  getList();
};
const getcharts = val => {
  console.log(activeWater.value);
  setTimeout(() => {
    getList();
  }, 100);
};
function getList() {
  loading.value = true;
  if (queryParams.value.timeUnit == "MONTH") {
    if (dateRange.value != null) {
      queryParams.value.startTime = `${dateRange.value[0]}-01 00:00:00`;
      queryParams.value.endTime = `${dateRange.value[1]}-01 00:00:00`;
    } else {
      queryParams.value.startTime = "";
      queryParams.value.endTime = "";
    }
  }
  if (queryParams.value.timeUnit == "DAY") {
    if (dateRange.value != null) {
      queryParams.value.startTime = `${dateRange2.value[0]}`;
      queryParams.value.endTime = `${dateRange2.value[1]}`;
    } else {
      queryParams.value.startTime = "";
      queryParams.value.endTime = "";
    }
  }
  wasteloadOutReport(queryParams.value).then((response: any) => {
    console.log(response);
    typeList.value = response;
    loading.value = false;
  });
}

const resetQuery = () => {
  queryParams.value = {
    reportType: "GL",
    dictWasteCode: [],
    startTime: "",
    endTime: "",
    classCode: props.classCode,
    timeUnit: "MONTH"
  };
  receiveName({
    classCode: props.classCode,
    physicalState: "LIQUID"
  }).then((response: any) => {
    //console.log(response);
    querychemicalList.value = response;
    queryParams.value.dictWasteCode = querychemicalList.value.map(item => item.itemValue);
  });
  queryParams.value.startTime = `${new Date().getFullYear()}-01-01 00:00:00`;
  queryParams.value.endTime = `${new Date().getFullYear()}-12-31 23:59:59`;
  dateRange.value = [`${new Date().getFullYear()}-01`, `${new Date().getFullYear()}-12`];
  handleQuery();
};
const { VITE_FANRUAN_BASE_URL, VITE_SERVE_API_STATIC_URL } = import.meta.env;
/** 导出按钮操作 */
function handleExport() {
  if (dateRange.value != null && dateRange.value.length > 0) {
    let Token = getToken().accessToken || "";
    // proxy.download("post", "/operation/api/v1/water/testQuality/pwMetalImpurity/export", queryParams.value, "水质检测-纯水金属阴阳离子.xlsx");
    let url = `${VITE_FANRUAN_BASE_URL}/webroot/decision/view/report?viewlet=water%252F%25E5%25BA%259F%25E5%25BC%2583%25E7%2589%25A9%25E8%25BD%25BD%25E5%2587%25BA%25E7%25BB%259F%25E8%25AE%25A1.cpt&token=${Token}&from=${queryParams.value.startTime}&to=${queryParams.value.endTime}&wasteCode=${queryParams.value.dictWasteCode}&reportType=${queryParams.value.reportType}&reportTypeName=${reportTypeName.value}&format=excel&extype=simple&classCode=${props.classCode}&timeUnit=${queryParams.value.timeUnit}&facCode=${localStorage.getItem("facCode") || ""}&apiHost=${VITE_SERVE_API_STATIC_URL}`;
    window.location.href = url;
  } else {
    PxMessage({
      message: "请选择时间后再导出",
      type: "error"
    });
  }
}
</script>

<style scoped lang="scss">
.water_col {
  height: 100%;
}

.waterdom {
  width: 100%;
  height: 100%;
  padding: 16px 24px;
  background-color: #fff;
  border-radius: 4px;
}

.first_width {
  width: calc(100% - 16px);
}

.model_chart {
  position: relative;
  width: 100%;
  height: calc(100% - 40px);
  margin-top: 10px;

  .co2img {
    position: absolute;
    top: 32px;
    left: 22px;
    width: 32px;
    height: 32px;
  }

  .titlep {
    position: absolute;
    top: 29px;
    left: 70px;
    font-size: 16px;
    font-weight: 400;
    color: #000;
  }

  .titlevalue {
    position: absolute;
    top: 55px;
    left: 70px;

    .titlevalue1 {
      float: left;
      font-size: 20px;
      font-weight: 600;
      line-height: 28px;
      color: #3b82f6;
    }

    .titlevalue1span {
      font-size: 16px;
      font-weight: 400;
      line-height: 22px;
      color: #4f4f4f;
    }

    .titlevalue2 {
      float: left;
      margin-top: 5px;
      margin-left: 20px;
      font-size: 14px;
      font-weight: 400;
      line-height: 20px;
      color: #000;
    }

    .titlevalue2span {
      display: inline-block;
      margin-left: 8px;
      font-size: 14px;
      line-height: 20px;
      color: #f87171;
    }
  }

  .co2mian {
    position: absolute;
    top: 112px;
    left: 0;
    width: 100%;
    height: 92px;
  }

  .co2mianleft {
    float: left;
    width: 50%;
    height: 100%;

    .co2mianleftp {
      width: calc(100% - 21px);
      height: 22px;
      padding-left: 20px;
      font-size: 14px;
      font-weight: 400;
      line-height: 20px;
      color: #000;
      border-right: 1px solid #cbcdd8;
    }
  }

  .co2mianright {
    float: left;
    width: 50%;
    height: 100%;

    .co2mianrightp {
      width: calc(100% - 45px);
      height: 22px;
      padding-left: 45px;
      font-size: 14px;
      font-weight: 400;
      line-height: 20px;
      color: #000;
    }
  }

  .co2mianleftp2 {
    margin-left: 20px;
    font-size: 16px;
    font-weight: 600;
    color: #3b82f6;

    .co2mianleftp2span {
      font-size: 14px;
      font-weight: 400;
      color: #4f4f4f;
    }
  }

  .co2mianleftp3 {
    float: left;
    margin-left: 20px;
    font-size: 14px;
    font-weight: 400;
    color: #000;

    .titlevalue2span {
      display: inline-block;
      margin-left: 8px;
      font-size: 14px;
      line-height: 20px;
      color: #34d399;
    }
  }
}

.percentage-value {
  display: block;
  margin-top: 10px;
  font-size: 26px;
}

.percentage-label {
  display: block;
  margin-top: 10px;
  font-size: 16px;
}

.percentage-value2 {
  display: block;
  margin-top: 10px;
  font-size: 20px;
}

.percentage-label2 {
  display: block;
  margin-top: 10px;
  font-size: 14px;
}

.percentage-value3 {
  display: block;
  margin-top: 10px;
  font-size: 20px;
  color: #f00;
}

.percentage-label3 {
  display: block;
  margin-top: 10px;
  font-size: 14px;
  color: #f00;
}

.jindu1 {
  margin: 24px 0 0 17px;
}

.jindu2 {
  margin: 38px calc((100% - 103px) / 2);
}

.jindu1p {
  width: calc(100% - 24px);
  margin-top: 0;
  font-size: 16px;
  text-align: center;
}

.jindu2p {
  width: 100%;
  margin-top: -40px;
  font-size: 14px;
  text-align: center;
}

:deep(.px-table) {
  .px-table__cell {
    padding: 6px 0;
  }

  .px-table__header-wrapper,
  .px-table__fixed-header-wrapper {
    th {
      background-color: #e7eefb !important;
    }
  }
}

.tableTop {
  display: flex;

  .topList {
    flex: 1;
    min-width: 125px;
    padding: 6px;
    font-size: 14px;
    font-weight: bold;
    line-height: 23px;
    color: #000;
    background-color: #e7eefb !important;
    border: 1px solid #dfdfdf;
    border-right: none;

    &:nth-last-child(1) {
      border-right: 1px solid #dfdfdf;
    }
  }
}

.tableMain {
  display: flex;

  .topList {
    flex: 1;
    min-width: 125px;
    padding: 6px;
    font-size: 14px;
    line-height: 23px;
    color: #000;
    border: 1px solid #dfdfdf;
    border-top: none;
    border-right: none;

    &:nth-last-child(1) {
      border-right: 1px solid #dfdfdf;
    }
  }
}

.export {
  position: absolute;
  top: 16px;
  right: 30px;
}
</style>
